package com.csliubo.eclipse.plugin.sqlgenerator.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import org.apache.commons.io.IOUtils;
import org.eclipse.jface.preference.IPreferenceStore;

import com.csliubo.eclipse.plugin.sqlgenerator.Activator;
import com.csliubo.eclipse.plugin.sqlgenerator.constants.OutputFormat;
import com.csliubo.eclipse.plugin.sqlgenerator.preferences.PreferenceConstants;


public class Config {

    private static String              methodName;
    private static Map<String, String> tableAndSql;
    private static IPreferenceStore    store = Activator.getDefault().getPreferenceStore();
    private static String              dir;

    public static void init(File file) throws IOException {
        Properties p = new Properties();
        tableAndSql = new HashMap<String, String>();
        InputStream is = new FileInputStream(file);
        p.load(is);
        for (Entry<Object, Object> entry : p.entrySet()) {
            if ("method".equals(entry.getKey())) {
                methodName = entry.getValue().toString();
                continue;
            }
            tableAndSql.put(entry.getKey().toString(), entry.getValue().toString());
        }
        IOUtils.closeQuietly(is);
        dir = file.getParent() + File.separator;
    }

    public static Map<String, String> getTableAndSqlMap() {
        return tableAndSql;
    }

    public static String getConnectionUrl() {
        return store.getString(PreferenceConstants.JDBC_CONNECTION_URL);
    }

    public static String getDBUser() {
        return store.getString(PreferenceConstants.DB_USER);
    }

    public static String getDBPassword() {
        return store.getString(PreferenceConstants.DB_PASSWORD);
    }

    public static String getDriverClass() {
        return store.getString(PreferenceConstants.JDBC_DRIVER_CLASS);
    }

    public static int getTabSize() {
        String tabSizeStr = store.getString(PreferenceConstants.TAB_SIZE);
        return Integer.valueOf(tabSizeStr);
    }

    public static String getTargetFilePath() {
        return dir + methodName;
    }

    public static String getDriverLocation() {
        return store.getString(PreferenceConstants.DRIVER_CLASS_LOCATION);
    }

    public static OutputFormat getOuputFormat() {
        String formatStr = store.getString(PreferenceConstants.OUTPUT_FORMAT);
        OutputFormat format = OutputFormat.getFormatByValue(formatStr);
        return format;
    }
}
